
$(document).ready(function () {
    Judgeidentity();
    initSize();
    initWebSocket()
    // initMenu()
    //获取当前时间
    // $("#time").showCurrentTime();


    layui.use(function () {

        var form = layui.form;
        element = layui.element;
        form.set({
            autocomplete: 'off' // 阻止 input 框默认的自动输入完成功能
        });
        // 表单验证
        form.verify({
            isInt: function (value, elem) {
                if (!/^\d+$/.test(value)) {
                    return '此项需填写整数';
                }
            }
        });

    });

})
var element;
var menuList = JSON.parse(localStorage.getItem('menu')) || []

/*初始化默认字体大小*/
function initSize() {
    //适应不同分辨率
    let fontSize;
    resize();
    window.onresize = resize;

    function resize() {

        let winW = window.innerWidth;

        if (winW < 1366) {
            winW = 1366;
        }
        fontSize = winW / 1920 * 100
        document.getElementsByTagName('html')[0].style.cssText = "font-size:" + fontSize + "px";
    }
}


// 顶部菜单切换
$('.header-menu-item').click(function (e) {
    $(e.currentTarget).addClass('active').siblings().removeClass('active');
})


// 生成菜单

var fullMenuList = []//无左侧菜单页面，变为下拉菜单

var dropMenu = ['ce2cda1e43f945b98180cc4e0553263c', 'afd22ee67c224a50a867a977bfadaddb'];//头部变成下拉菜单的页面id



if (menuList?.filter(item => { return dropMenu.includes(item.id) }).length > 0) {
    menuList?.filter(item => { return dropMenu.includes(item.id) })[0].children.map(item => {
        fullMenuList.push(item.path)
    })
}

// 入口页菜单
entryMenu = () => {



    $('.entry-item').empty().append(menuList.reduce((x, y) => {

        let path = y.path == "xxqg" ? 'xxqg' : y?.children?.[0]?.children?.[0]?.path


        return x + `
        <div class="card"  onclick=entrySubMenu("${path}")>
            <div class="card-info">
                <div class="img" style="background-image: url(../static/img/menu/${y.icon});"></div>
                <p class="title">${y.name}</p>
            </div>
        </div>
        `
    }, ''))

}

// 入口页进入
entrySubMenu = (path) => {
    if (path === 'xxqg') {//跳转学习强国外链
        window.open('https://www.xuexi.cn/')

    } else {
        window.location.href = "../html/" + path;
    }

}


var tempHerf = window.location.href.split('/')

initSubMenu = () => {

    $('#resetSearch').click();//清空查询栏


    var topParentId = getTopLevelIdByName(menuList, window.location.href.split("/").pop());

    var headerTemp = menuList.filter(item => { return item.id == topParentId })[0]?.children;

    var headerParentId = getTopLevelIdByName(headerTemp, window.location.href.split("/").pop());


    // 头部一级菜单
    $('.header-menu').empty().append(headerTemp?.reduce((x, y) => {

        var active = '', dropId = ''

        if (y.id == headerParentId) {
            active = 'active'
        } else {
            active = ''
        }
        if (y.name === '智能训练' || y.name === '人员管理') {
            dropId = 'dropdown-menu'

        } else {
            dropId = ''

        }

        return x + `<div class="header-menu-item ${active}" id="${dropId}" onclick=jumpMenu("${y.children ? (y.children[0].path) : (y.path)}")><span>${y.name}${dropId == '' ? '' : '<i style="position: absolute;" class="layui-icon layui-icon-triangle-d"></i>'}</span></div>`



    }, `<div class="header-tool"></div>
    <div class="header-menu-item" onclick=jumpMenu("entry.html")><span>模块选择</span></div>
    `))

    workTaskCount()

    // 当前选中的一级菜单下的所有子菜单
    var subMenu = headerTemp?.filter(function (item) {
        return item.id == headerParentId;
    }) || []

    // 智能训练子菜单
    var trainMenu = headerTemp?.filter(function (item) {

        return dropMenu.includes(item.id);
    })



    if (trainMenu?.length > 0) {
        var subL = [];
        trainMenu[0].children.forEach(element => {

            subL.push({
                title: element.name,
                path: element.path
            })

        });

        layui.dropdown.render({

            elem: '#dropdown-menu',

            data: subL,

            click: function (obj) {

                window.location.href = "../html/" + obj.path;

            }

        });

    }

    var str = ''

    if (!subMenu[0].children) {
        subMenu[0].children = []
    }
    str = subMenu[0].children.reduce((x, y) => {

        var active = ''


        if (window.location.href.indexOf(y.path) > -1 && y.path != '') {
            active = 'layui-this'
        } else {
            active = ''
        }

        var strSub = '';
        if (y.children) {
            strSub = y.children.reduce((x1, y1) => {
                var subActive = ''

                if (window.location.href.indexOf(y1.path) > -1 && y1.path != '') {
                    active = 'layui-this layui-nav-itemed'
                    subActive = 'layui-this'
                } else {
                    subActive = ''
                }

                return x1 + `<dd class="${subActive}" style="padding-left: 0.3rem;"><a href="${(y1.path == "" || y1.path == null) ? 'javascript:;' : y1.path}">${y1.name}</a></dd>`

            }, '<dl class="layui-nav-child">')
            strSub = strSub + '</dl>'
        }


        return x + `<li class="layui-nav-item ${active}">
                         <a href="${(y.path == "" || y.path == null) ? 'javascript:;' : y.path}">
                            <div class="sub-menu-item"><img src="../static/img/menu/${y.icon}">${y.name}</div>
                         </a>
                        ${strSub}
                    </li>`

    }, '<ul class="layui-nav layui-nav-tree layui-nav-side" lay-accordion lay-filter="sub-filter-nav">')
    str = str + '</ul>'

    $('.contain-menu').empty().append(str)
    layui.element.render('nav', 'sub-filter-nav');
}


function jumpMenu(path) {

    if (((fullMenuList.includes(tempHerf[tempHerf.length - 1])) && (fullMenuList.includes(path))) || (["firemenCard.html", "personnelStatistics.html"].includes(path))) {

        return
    }

    window.location.href = "../html/" + path;
}

function getTopLevelIdByName(treeData, targetName) {

    // 构建父节点映射表
    const parentMap = new Map();
    (function buildParentMap(nodes, parent) {
        nodes?.forEach(node => {
            if (parent) parentMap.set(node.id, parent);
            if (node.children) buildParentMap(node.children, node);
        });
    })(treeData, null);

    // 查找目标节点
    let targetNode = null;
    (function findNode(nodes) {
        for (const node of nodes || []) {
            if (node.path == targetName) {
                targetNode = node;
                return true;
            }
            if (node.children && findNode(node.children)) return true;
        }
        return false;
    })(treeData);

    if (!targetNode) return null;

    // 回溯查找最顶层祖先
    let currentNode = targetNode;
    while (true) {
        const parent = parentMap.get(currentNode.id);
        if (!parent) return currentNode.id;
        currentNode = parent;
    }
}

// 侧边菜单切换
function checkSubMenu(href) {

    window.location.href = "../html/" + href

}


// 查询头部代办已办
function workTaskCount() {

    new AjaxChain()
        .setUrl('/work/task/count/lastest')
        .then(data => {

            $('.header-tool').empty().append(`
                <div class="header-supply" onclick=showHeaderPlanTable(1)>日<sup style="background-color: #5a81ba;">${data.dayToDo}</sup></div>
                <div class="header-supply" onclick=showHeaderPlanTable(2)>周<sup style="background-color: #6aac52;">${data.weekToDo}</sup></div>
                <div class="header-supply" onclick=showHeaderPlanTable(3)>月<sup style="background-color: #f2ae43;">${data.monthToDo}</sup></div>
                <div class="header-supply" onclick=showHeaderPlanTable(4)>季度<sup style="background-color: #d4383b;">${data.seasonToDo}</sup></div>
                <div class="header-supply" onclick=showHeaderPlanTable(5)>半年<sup style="background-color: #816243;">${data.halfToDo}</sup></div>
                <div class="header-supply" onclick=showHeaderPlanTable(6)>年度<sup style="background-color: #77224a;">${data.yearToDo}</sup></div>
                <div class="header-supply" onclick=planPic()>一张图</div>
                <img class="changePwd" onclick=changePwd() src="../static/img/user.png" title="修改密码">
                <img class="logout" onclick=logout() src="../static/img/logout.png" title="退出登录">
            `)

        })
        .catch(err => {
            console.error('登录过期，请重新登录:', err);
            loginOut()
        })
        .send();

}


function showHeaderPlanTable(type) {

    layer.open({
        type: 1, // page 层类型
        area: ['80%', '70%'],
        title: '任务列表',
        shade: 0.6, // 遮罩透明度
        shadeClose: true, // 点击遮罩区域，关闭弹层
        maxmin: false, // 允许全屏最小化
        anim: 0, // 0-6 的动画形式，-1 不开启
        content: `<div style="width: 100%;height: 100%;display: flex;padding: 0.2rem;"><table id="table-header" lay-filter="table-header" style="width: 100%;height: 100%;"></table></div>`,
        success: function () {
            queryHeaderPlanTable(type)
        }
    });

}


// 查询表格数据
queryHeaderPlanTable = (type) => {
    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table-header'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/work/task/list/lastest"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: {
                type: type
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "data": res.result //解析数据列表
                };
            }
            , cols: [[ //标题栏
                { field: 'name', title: '计划名称', align: "center" }
                , { field: 'content', title: '详细记录', align: "center" }
                , { field: 'typeDesc', title: '周期类型', align: "center" }
                , { field: 'manageTypeDesc', title: '主要负责人', align: "center" }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: 100,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool" style="color: #bbb;">
                                 ${d.status == 2 ? "已完成" : `<div onclick=handlePlan("${d.id}","${d.type}") style="width: auto;height: 0.28rem;" class="layui-btn"> 处理</div>`}
                              </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , done: function (res, curr, count) {
                // $('.layui-table-cell').height($('#table-header').height() / 20);
            },

        });

    });
}

// 完成计划
function handlePlan(id, type) {


    layer.prompt({ title: '请输入任务描述', formType: 2 }, function (value, index, elem) {

        new AjaxChain()
            .setUrl('/work/task/done')
            .setMethod('post')
            .setData(JSON.stringify({
                id: id,
                doneDesc: value
            }))
            .then(data => {
                layer.msg('已完成该工作', { icon: 1, time: 1500 });

                if (type) {
                    queryHeaderPlanTable(type)
                } else {
                    generateData()
                }

            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();

        layer.close(index)

    });



}


// 打开计划一张图

function planPic() {
    var index = layer.open({
        type: 2,
        title: false,
        closeBtn: 2,
        isOutAnim: true,
        shadeClose: true,
        area: ['100%', '100%'],
        content: 'planTable.html',


    });
}


/*判断字段是否为空或者*/
function checkNullOrEmpty(field) {

    if (field == null || field === "") {
        return ''
    } else {
        return field
    }

}

/**/

function logout() {
    layer.confirm('确定退出系统？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        loginOut();
    });
}

function loginOut() {
    $.ajax({
        url: '/rest/fstation/logout',
        type: "post",
        contentType: "application/json",
        headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        },
        success: function (result) {
            localStorage.setItem('sessionId', "");


            window.location.href = "../html/login.html";
        },
        error: function (result) {

            localStorage.setItem('sessionId', "");
            window.location.href = "../html/login.html";
        }
    })
}

// 登录信息验证
function Judgeidentity() {
    var isLogin = localStorage.getItem('sessionId');
    if (isLogin == null || isLogin == "") {
        window.location.href = "../html/login.html";
    }
}

// 将扁平数据转换为树形结构
function buildTree(data) {

    const idMapping = data.reduce((acc, el, i) => {
        acc[el.id] = i;
        return acc;
    }, {});

    let root = [];
    data.forEach(el => {
        // 判断是否为顶层节点
        if (el.pId === null || el.pId == "") {
            root.push(el);
            return;
        }
        // 找到父节点并添加到它的 children 数组中
        const parentEl = data[idMapping[el.pId]];
        parentEl.children = [...(parentEl.children || []), el];
    });
    return root;
}


// 用户修改密码
changePwd = () => {
    layer.prompt({
        title: '请输入新密码'
        , formType: 1
        , success: function (layero, index) {
            var promptInput = layero.find('input');
            promptInput.attr('autocomplete', 'off');
        }
    },
        function (value, index, elem) {

            if (value === '') return elem.focus();

            passwordOne = value;

            layer.close(index);

            layer.prompt({
                title: '请确认新密码'
                , formType: 1
                , success: function (layero, index) {
                    var promptInput = layero.find('input');
                    promptInput.attr('autocomplete', 'off');
                }
            },
                function (valueNew, indexNew) {

                    if (valueNew === '') return elem.focus();

                    passwordTwo = valueNew;
                    layer.close(indexNew);
                    if (passwordOne == passwordTwo) {

                        new AjaxChain()
                            .setUrl('/user/password/update')
                            .setMethod('post')
                            .setData(JSON.stringify({
                                id: JSON.parse(localStorage.getItem("userInfo")).userId,
                                passwordOne: passwordOne,
                                passwordTwo: passwordTwo,
                            }))
                            .then(data => {
                                layer.msg('修改成功', { icon: 1, time: 2000 });
                                loginOut()
                            })
                            .catch(err => {
                                console.error('请求异常:', err);
                            })
                            .send();



                    } else {
                        layer.msg('两次密码输入不一致，请重新设置')
                    }


                });

        });
}

// 计算年龄
$.calculateAge = function (birthDate) {
    var today = new Date();
    var birthDateObj = new Date(birthDate);
    var age = today.getFullYear() - birthDateObj.getFullYear();
    var monthDiff = today.getMonth() - birthDateObj.getMonth();

    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDateObj.getDate())) {
        age--;
    }
    return age;
};

// 图片放大预览
function showPhoto(photoPath) {
    if (photoPath) {
        layer.photos({
            photos: {
                "data": [
                    {
                        "src": "/images/" + photoPath,
                    }
                ]
            },
            footer: false
        });
    } else {
        layer.msg('暂未上传', { time: 1000 })
    }
}
// 进度条
function showProgress(msg, callBack, speed) {

    layer.msg(`<div class="layui-progress layui-progress-big" lay-filter="filter-progress">
        <div style="background: linear-gradient(to left,#05ffa1,#74b7ff);" class="layui-progress-bar" lay-percent="0%"></div>
    </div>`, {
        time: 50000,
        area: '30%', offset: 't', shade: 0.5,
        success: function (layero, index, that) {
            element.render('progress', 'demo-filter-progress');
            var n = 0;

            var timer = setInterval(function () {
                n = n + Math.random() * 10 | 0;

                if (n > 100) {

                    n = 100;

                    clearInterval(timer);

                    layer.close(index);

                    callBack()

                    layer.msg(msg, {
                        time: 1000,
                    })
                }

                element.progress('filter-progress', n + '%');

            }, speed + Math.random() * speed);

        }
    },);

}


function ajaxPrefix() {
    return '/rest/fstation'
}

function AjaxRequest(url, callBack, parms, type, async) {
    $.ajax({
        url: ajaxPrefix() + url,
        type: type ? type : 'get',
        data: parms ? JSON.stringify(parms) : '',
        traditional: true,
        headers: {
            SessionId: 'fbbd77cb80464ea1933c4768927bbb01'
        },
        async: false,
        contentType: "application/json",
        success: function (result) {
            callBack(result);
        }
    });
}

ajaxUploadFile = (url, callBack, formData) => {
    $.ajax({
        url: ajaxPrefix() + url,
        type: 'post',
        data: formData,
        dataType: "json",
        cache: false, headers: {
            SessionId: JSON.parse(localStorage.getItem('sessionId'))
        },
        processData: false,
        contentType: false,
        success: function (result) {
            callBack(result);
        }
    })
}


// websocket连接
var tryTime = 0, socket = null;
function initWebSocket() {
    socket = new WebSocket('ws://zhjy.njdtwise.net:8181/rest/fstation/websocket/' + JSON.parse(localStorage.getItem("userInfo")).orgId);

    socket.onopen = () => {
        console.log('Connected');
    };

    socket.onmessage = (event) => {


        handleWebSocket(event.data)
    };

    socket.onclose = function () {
        // 重试
        if (tryTime < 5) {
            // 先每隔五秒重连一次，重复五次
            setTimeout(function () {
                socket = null;
                tryTime++;
                initWebSocket();
            }, 5 * 1000);
        } else {
            //五次后每30分钟尝试重连
            setTimeout(function () {
                socket = null;
                initWebSocket();
            }, 30 * 60 * 1000);
        }
    };

    // 页面关闭前主动断开连接
    window.addEventListener('beforeunload', () => {
        socket.close();
    });
}
function handleWebSocket(data) {
    data = eval("(" + data + ")");

    // DEVICE(1, "设备告警类"),
    // SCORE(2, "训练成绩类"),
    // SCORECHART(3, "训练成绩图表类"),
    // CARDNO(4, "卡号")

    switch (data.dataType) {
        case 1:

            break;
        case 2:

            showRecordList();
            drawGun();

            break;
        case 3:

            break;
        case 4:
            if (window.location.href.indexOf('materials.html') > -1) {
                if ($('#edit-offset').find('input[name=code]').length > 0) {
                    $('#edit-offset').find('input[name=code]').val(data.cardNo)
                }
                else {

                    queryMaterialsDetail(data.cardNo);
                }
            } else {
                layer.confirm('该操作需在物资页面进行，是否马上跳转', { icon: 3 }, function () {

                    window.location.href = "materials.html";

                });

            }


            break;

        default:
            break;
    }
}




// 封装接口调用
class AjaxChain {
    constructor() {
        this.config = {
            url: '',
            type: 'GET',
            data: {},
            dataType: 'json',
            contentType: "application/json",
            layer: false, // 是否显示加载层
            layerOptions: {} // 加载层配置
        };
        this.layerId = null;
    }

    setUrl(url) {
        this.config.url = url;
        return this;
    }

    setMethod(method) {
        this.config.type = method.toUpperCase();
        return this;
    }

    setData(data) {
        this.config.data = data;
        return this;
    }

    setContentType(type) {
        this.config.contentType = type;
        return this;
    }

    // 启用加载层
    enableLayer(msg, callBack, speed) {
        var speed = speed || 100


        showProgress(msg, callBack, speed)
        return this;
    }

    // 成功回调
    then(successCallback) {
        this.config.success = (res) => {
            if (this.config.layer && this.layerId) layer.close(this.layerId);

            if (res.message === 'OK') {
                successCallback(res.result);

            } else {
                layer.msg(hasChinese(res.result) ? res.result : '请求失败', { icon: 5 });
            }
        };
        return this;
    }

    // 失败回调
    catch(errorCallback) {
        this.config.error = (xhr, status, error) => {
            if (this.config.layer && this.layerId) layer.close(this.layerId);
            errorCallback(error);
            layer.msg('请求失败: ' + status, { icon: 5 });

        };
        return this;
    }

    // 发送请求
    send(progress) {
        const _this = this;

        if (this.config.layer) {
            this.layerId = layer.open(_this.config.layerOptions);
        }

        $.ajax({
            url: ajaxPrefix() + this.config.url,
            type: this.config.type,
            data: this.config.data,
            dataType: this.config.dataType,
            contentType: this.config.contentType,
            headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            },
            success: this.config.success || function (res) {
                // 默认成功处理
            },
            error: this.config.error || function (xhr) {
                // 默认错误处理
            },
            complete: function () {
                if (_this.config.layer && _this.layerId) {
                    layer.close(_this.layerId);
                }
            }
        });

        return this;
    }
}

// 判断返回的结果有没有中文
function hasChinese(str) {
    return /[\u4E00-\u9FFF]/.test(str);
}

// 封装下拉选择字段获取 SELECTTYPE
class ST {
    //设备类型
    device(returnType) {

        var typeArr = [
            { type: 1, name: 'RFID网关' },
            { type: 2, name: '落地感应装置网关' },
            { type: 3, name: '广播' },
            { type: 4, name: '人脸识别' },
            { type: 5, name: '手动报警监测' },
            { type: 6, name: '可燃气体监测' },
            { type: 7, name: '远程断电' },
            { type: 8, name: '读卡器' },
        ]

        let str = typeArr.reduce((x, y) => {
            return x + `<option value="${y.type}">${y.name}</option>`
        }, '<option value="">设备类型</option>')

        return returnType ? typeArr : str;
    }
    //计量单位类型
    unit(returnType) {

        var typeArr = ['包', '盒', '瓶', '支', '袋', '头/份', 'kg', '丸', '桶', '粒', '罐', '箱', 'g', '管', 'ml', '片', '捆', '只', '张', '套', '台', '双', '升', '米', '块', '卷', '节', '根', '个', '付', '吨', '把', '组', '件', '圈', '斤', '条', '本', '副', '拓', '提', '颗', '万']

        let str = typeArr.reduce((x, y) => {
            return x + `<option value="${y}">${y}</option>`
        }, '<option value="">请选择</option>')

        return returnType ? typeArr : str;
    }

    // 训练项目类型
    project(returnType) {
        var typeArr = [
            { type: 1, name: '爬绳' },
            { type: 2, name: '挂钩梯攀爬' },
            { type: 3, name: '号操' },
            { type: 4, name: '负重登10楼' },
            { type: 5, name: '室内体能' },
            { type: 6, name: '一人扶梯一人爬' }
        ]

        let str = typeArr.reduce((x, y) => {
            return x + `<option value="${y.type}">${y.name}</option>`
        }, '<option value="">项目类型</option>')

        return returnType ? typeArr : str;
    }

    // 训练环节
    projectNode(returnType) {
        var typeArr = [
            { type: 0, name: '起点' },
            { type: 99, name: '终点' },
            { type: 1, name: '环节1' },
            { type: 2, name: '环节2' },
            { type: 3, name: '环节3' },
            { type: 4, name: '环节4' },
            { type: 5, name: '环节5' },
            { type: 6, name: '环节6' },
            { type: 7, name: '环节7' },
            { type: 8, name: '环节8' },
            { type: 9, name: '环节9' },
            { type: 10, name: '环节10' },
        ]

        let str = typeArr.reduce((x, y) => {
            return x + `<option value="${y.type}">${y.name}</option>`
        }, '<option value="">请选择环节</option>')

        return returnType ? typeArr : str;
    }


    // 计划负责人
    manageType(returnType) {
        var typeArr = [
            { type: 1, name: '站长' },
            { type: 2, name: '政治指导员' },
            { type: 3, name: '队站主官' },
            { type: 4, name: '队站干部' },
            { type: 5, name: '班长' },
            { type: 6, name: '值班干部' },
            { type: 7, name: '值班班长' },
            { type: 8, name: '交班干部' },
            { type: 9, name: '党支部书记' },
            { type: 10, name: '团支部书记' },
            { type: 11, name: '党小组组长' },
            { type: 12, name: '经委会' },
            { type: 13, name: '经委会委员' },
            { type: 14, name: '通信班' }
        ]

        let str = typeArr.reduce((x, y) => {
            return x + `<option value="${y.type}">${y.name}</option>`
        }, '<option value="">主要负责人</option>')

        return returnType ? typeArr : str;
    }



    // 物资类型列表
    materialType = async (returnType, key, value) => {
        try {
            if (returnType) {
                const { rawData } = await this._fetchData('/material/type/select', key ? key : 'id', key ? key : 'name');
                return rawData;
            } else {
                const { options } = await this._fetchData('/material/type/select', key ? key : 'id', key ? key : 'name');
                return options;
            }

        } catch (error) {
            console.error('获取数据失败:', error);
            return [];
        }
    }

    // 消防员列表
    firemen = async (returnType, key, value) => {
        try {
            if (returnType) {
                const { rawData } = await this._fetchData('/person/list/all', key ? key : 'id', key ? key : 'name');
                return rawData;
            } else {
                const { options } = await this._fetchData('/person/list/all', key ? key : 'id', key ? key : 'name');
                return options;
            }

        } catch (error) {
            console.error('获取数据失败:', error);
            return [];
        }
    }

    // 自定义创建训练项目类型
    trainProject = async (returnType, key, value, type) => {

        try {
            if (returnType) {
                const { rawData } = await this._fetchData('/train/project/select?type=' + (type ? type : ''), key ? key : 'id', key ? key : 'name', (type ? '项目筛选' : null));
                return rawData;
            } else {
                const { options } = await this._fetchData('/train/project/select?type=' + (type ? type : ''), key ? key : 'id', key ? key : 'name', (type ? '项目筛选' : null));
                return options;
            }

        } catch (error) {
            console.error('获取数据失败:', error);
            return [];
        }
    }



    // 通用数据获取方法
    _fetchData = (url, key, value, optionName) => {
        return new Promise((resolve, reject) => {
            new AjaxChain()
                .setUrl(url)
                .then(data => resolve({
                    rawData: data,  // 原始数据
                    options: data.reduce((html, item) =>
                        html + `<option value="${item[key]}">${item[value]}</option>`,
                        '<option value="">' + (optionName ? optionName : '请选择') + '</option>'
                    )
                }))
                .catch(error => reject(error))
                .send();
        });
    }
}

